/**
 * 演示程序当前的 “注册/登录” 等操作，是基于 “本地存储” 完成的
 * 当您要参考这个演示程序进行相关 app 的开发时，
 * 请注意将相关方法调整成 “基于服务端Service” 的实现。
 **/
(function($, owner) {
	/** 
	 * app版本号
	 */
	owner.app_version = 2;
	/**
	 * 用户登录
	 **/
	owner.login = function(loginInfo, callback) {
		callback = callback || $.noop;
		loginInfo = loginInfo || {}; 
		loginInfo.account = loginInfo.account || '';
		loginInfo.password = loginInfo.password || '';
		if (loginInfo.account.length < 5) {
			return callback('账号最短为 5 个字符');
		}
		if (loginInfo.password.length < 6) {
			return callback('密码最短为 6 个字符');
		}
		
		mui.ajax(this.getUrl()+'userinfo/login',{
			data:{
				username:loginInfo.account,
				password:loginInfo.password
			},
			contentType: "application/json;charset=utf-8",
			dataType:'json',//服务器返回json格式数据
			type:'post',//HTTP请求类型
			timeout:10000,//超时时间设置为10秒；
			success:function(data){ 
				console.log("user:"+JSON.stringify(data))
				if(data.errCode === "000000") {
					owner.setUserInfo(data.data);
					callback();
				}else {
					return callback('用户名或密码错误');
				}
			},
			error:function(xhr,type,errorThrown){
				return callback('服务器断开连接...');
			}
		});
	};

	owner.createUserInfo = function(userInfo, callback) {
		owner.setUserInfo(userInfo);
		return callback();
	};
	
	
	/**
	 * 新用户注册
	 **/
	owner.reg = function(regInfo, callback) {
		callback = callback || $.noop;
		regInfo = regInfo || {};
		regInfo.account = regInfo.account || '';
		regInfo.password = regInfo.password || '';
		if (regInfo.code.length < 1) {
			return callback('验证码不能为空');
		}
		if (regInfo.username.length < 5) {
			return callback('账号最短需要 5 个字符');
		}
		if (regInfo.nickname.length < 2) {
			return callback('昵称最短需要 2 个字符');
		}
		if (regInfo.password.length < 6) {
			return callback('密码最短需要 6 个字符');
		}
		if (regInfo.headImageUrl.length < 6) {
			return callback('请上传头像...');
		}
		if (!checkEmail(regInfo.email)) {
			return callback('邮箱地址不合法');
		}
		mui.ajax(app.getUrl()+"userinfo/userReg",{
			data:JSON.stringify(regInfo),
			contentType: "application/json;charset=utf-8",
			dataType:'json',//服务器返回json格式数据
			type:'post',//HTTP请求类型
			timeout:10000,//超时时间设置为10秒；
			success:function(data){
				if(data.errCode === "000000") { 
					return callback();
				}else {
					return callback("注册失败!失败原因:"+data.errMsg);
				}
			},
			error:function(xhr,type,errorThrown){
				return callback("无法连接服务器...");
			}
		});
	};

	/**
	 * 获取当前状态
	 **/
	owner.getState = function() {
		var stateText = localStorage.getItem('$state') || "{}";
		return JSON.parse(stateText);
	};
	
	/**
	 * 获取当前用户
	 **/
	owner.getUserInfo = function() {
		//测试
		// var userInfo = {"userOpenId":"oU5Yyt84BiQK48Fdl7QQ7LjsakfU","userNickName":"Mr.Chen333333333333","userAvatarUrl":"https://thirdwx.qlogo.cn/mmopen/vi_32/NwibWw6XyvjfrYDKUCAhxVpK3bDiaR7MyXK47KYEcNnh7hR58cexAvbKZwU2ia4DiaXgGmIF3aud5G8tib8h2VzMOjA/132","userScore":105,"userLevel":9,"userSpecies":0};
		// return userInfo;
		var userInfo = localStorage.getItem('userInfo') || "{}";
		return JSON.parse(userInfo);
	};
	
	owner.bgMusicPlayer = function() {
		bgMusic = plus.audio.createPlayer( "/audio/bg.mp3" ); //播放音乐
	    var num = bgMusic.getDuration();//获取音频总长度number
	    setTimeout(function(){//延时获取，否则可能没有返回长度
	        var num = bgMusic.getDuration();
	    },100)
	    bgMusic.play( function () {//播放完成回调
			owner.bgMusicPlayer();
	    }, function ( e ) {//失败回调
	    } ); 
	}
	
	owner.bgMusicPause = function(){//暂停播放
	    bgMusic.pause();
	}
	
	owner.bgMusicresume = function(){//恢复播放
	    bgMusic.resume();
	}
	
	
	
	owner.gameMusicPlayer = function() {//播放音乐
	    gameMusic = plus.audio.createPlayer( "/audio/game.mp3" );
	    var num = gameMusic.getDuration();//获取音频总长度number
	    setTimeout(function(){//延时获取，否则可能没有返回长度
	        var num = gameMusic.getDuration();
	    },100)
	    gameMusic.play( function () {//播放完成回调
			owner.gameMusicPlayer();
	    }, function ( e ) {//失败回调
	    } ); 
	}
	
	owner.gameMusicPause = function(){//暂停播放
	    gameMusic.pause();
	}
	
	owner.gameMusicresume = function(){//恢复播放
	    gameMusic.resume();
	}
	/**
	 * 获取ip地址或域名
	 **/
	owner.getUrl = function() {
		// return "http://192.168.185.122:18081/";
		return "http://47.92.67.168:18081/";
	};
	/**
	 * 获取websocket连接
	 */
	owner.getWebSocketUrl = function() {
		// return "http://localhost:8089/";
		return "ws://47.92.67.168:9999/ws";
	};
	/**
	 * 设置当前状态
	 **/
	owner.setState = function(state) {
		state = state || {};
		localStorage.setItem('$state', JSON.stringify(state));
		//var settings = owner.getSettings();
		//settings.gestures = '';
		//owner.setSettings(settings);
	};
	/**
	 * 设置当前用户
	 **/
	owner.setUserInfo = function(userInfo) {
		if(userInfo.token === null || userInfo.token === undefined) {
			var token = this.getUserInfo().token;
			userInfo.token = token;
		}
		userInfo = userInfo || {};
		localStorage.setItem('userInfo', JSON.stringify(userInfo));
	};

	var checkEmail = function(email) {
		email = email || '';
		return (email.length > 3 && email.indexOf('@') > -1);
	};

	/**
	 * 找回密码
	 **/
	owner.forgetPassword = function(email, callback) {
		callback = callback || $.noop;
		if (!checkEmail(email)) {
			return callback('邮箱地址不合法');
		}
		return callback(null, '新的随机密码已经发送到您的邮箱，请查收邮件。');
	};

	/**
	 * 获取应用本地配置
	 **/
	owner.setSettings = function(settings) {
		settings = settings || {};
		localStorage.setItem('$settings', JSON.stringify(settings));
	}

	/**
	 * 设置应用本地配置
	 **/
	owner.getSettings = function() {
			var settingsText = localStorage.getItem('$settings') || "{}";
			return JSON.parse(settingsText);
		}
		/**
		 * 获取本地是否安装客户端
		 **/
	owner.isInstalled = function(id) {
		if (id === 'qihoo' && mui.os.plus) {
			return true;
		}
		if (mui.os.android) {
			var main = plus.android.runtimeMainActivity();
			var packageManager = main.getPackageManager();
			var PackageManager = plus.android.importClass(packageManager)
			var packageName = {
				"qq": "com.tencent.mobileqq",
				"weixin": "com.tencent.mm",
				"sinaweibo": "com.sina.weibo"
			}
			try {
				return packageManager.getPackageInfo(packageName[id], PackageManager.GET_ACTIVITIES);
			} catch (e) {}
		} else {
			switch (id) {
				case "qq":
					var TencentOAuth = plus.ios.import("TencentOAuth");
					return TencentOAuth.iphoneQQInstalled();
				case "weixin":
					var WXApi = plus.ios.import("WXApi");
					return WXApi.isWXAppInstalled()
				case "sinaweibo":
					var SinaAPI = plus.ios.import("WeiboSDK");
					return SinaAPI.isWeiboAppInstalled()
				default:
					break;
			}
		}
	}
	
	
}(mui, window.app = {}));